package com.heima.wemedia.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.heima.api.feign.ApArticleFeignClient;
import com.heima.audit.baidu.BaiduImageScan;
import com.heima.audit.baidu.BaiduTextScan;
import com.heima.file.service.FileStorageService;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.wemedia.dtos.WmNewsDto;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.service.ShenHeService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageBuilder;
import org.springframework.amqp.core.MessageDeliveryMode;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.*;

/**
 * @Description ShenHeServiceImpl
 * @Author GGBond
 * @Date 2024-11-27
 */
@Service
public class ShenHeServiceImpl implements ShenHeService {

    @Autowired
    private BaiduImageScan baiduImageScan;

    @Autowired
    private BaiduTextScan baiduTextScan;

    @Autowired
    private FileStorageService fileStorageService;

    @Autowired
    private WmNewsMapper wmNewsMapper;

    @Autowired
    private ApArticleFeignClient apArticleFeignClient;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Override
    public void shenHe(WmNewsDto dto) {

        CorrelationData correlationData = new CorrelationData(UUID.randomUUID().toString());

        WmNews wmNews = wmNewsMapper.selectById(dto.getId());
        String text = new String();
        //获取文章的标题和标签
        text = text + dto.getTitle() + dto.getLabels();

        //获取文章内容
        String content = dto.getContent();
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            List<Map<String, String>> result = objectMapper.readValue(content, objectMapper.getTypeFactory().constructCollectionType(ArrayList.class, HashMap.class));
            //把所有文字放在text
            for (Map<String, String> map : result) {
                if ("text".equals(map.get("type"))) {
                    text = text + map.get("value");
                }
            }
            //对文字进行审核
            if (StringUtils.isNotBlank(text)) {
                Integer textScan = baiduTextScan.textScan(text);
                if (textScan == 2) {
                    wmNews.setStatus((short) 2);
                    wmNews.setReason("审核失败，文本中包含敏感词");
                    wmNewsMapper.update(wmNews, null);
                    return;
                }
                if (textScan == 3) {
                    wmNews.setStatus((short) 3);
                    wmNews.setReason("人工审核中");
                    wmNewsMapper.update(wmNews, null);
                    return;
                }
                if (textScan == 4) {
                    wmNews.setStatus((short) 3);
                    wmNews.setReason("人工审核中");
                    wmNewsMapper.update(wmNews, null);
                    return;
                }
            }
            //对图片进行审核
            List<String> images = new ArrayList<>();
            //获取封面图片
            if (dto.getImages() != null && dto.getImages().size() > 0) {
                images.addAll(dto.getImages());
            }
            //获取内容中的图片
            for (Map<String, String> map : result) {
                if ("image".equals(map.get("type"))) {
                    images.add(map.get("value"));
                }
            }
            for (String image : images) {
                byte[] bytes = fileStorageService.downLoadFile(image);
                Integer imagedScan = baiduImageScan.imageScan(bytes);
                if (imagedScan == 2) {
                    wmNews.setStatus((short) 2);
                    wmNews.setReason("审核失败，文本中包含敏感词");
                    wmNewsMapper.update(wmNews, null);
                    return;
                }
                if (imagedScan == 3) {
                    wmNews.setStatus((short) 3);
                    wmNews.setReason("人工审核中");
                    wmNewsMapper.update(wmNews, null);
                    return;
                }
                if (imagedScan == 4) {
                    wmNews.setStatus((short) 3);
                    wmNews.setReason("人工审核中");
                    wmNewsMapper.update(wmNews, null);
                    return;
                }
            }
            //将当前时间转成long类型的格式
            ZonedDateTime zonedDateTime = LocalDateTime.now().atZone(ZoneId.systemDefault());
            long epochMilli = zonedDateTime.toInstant().toEpochMilli();

            if (dto.getPublishTime().getTime() > epochMilli)  {
                wmNews.setStatus((short) 8);
                wmNews.setReason("审核通过，待发布");
                wmNewsMapper.update(wmNews, null);
                ArticleDto articleDto = BeanUtil.toBean(wmNews, ArticleDto.class);
                articleDto.setId(wmNews.getArticleId());
                String jsonString = JSON.toJSONString(articleDto);
                Message message = MessageBuilder.withBody(jsonString.getBytes(StandardCharsets.UTF_8))
                        .setDeliveryMode(MessageDeliveryMode.PERSISTENT)
                        .setHeader("x-delay", dto.getPublishTime().getTime() - epochMilli)
                        .build();
                rabbitTemplate.convertAndSend("delay.exchange","delay.key",message,correlationData);
            } else {
                wmNews.setStatus((short) 9);
                wmNews.setReason("审核通过");
                wmNewsMapper.update(wmNews, null);
                ArticleDto articleDto = BeanUtil.toBean(wmNews, ArticleDto.class);
                articleDto.setId(wmNews.getArticleId());
                apArticleFeignClient.save(articleDto);
            }
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
    }
}
